package 链表与双指针.m03.d07;

import 链表与双指针.ListNode;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode newHead = new ListNode();
        newHead.next = head;
        ListNode pprev = null, cur = newHead;
        for(int i = 1; i < left; i++) {
            newHead = newHead.next;
        }
        pprev = newHead;
        newHead = newHead.next;
        ListNode prev = null, next = newHead.next, tmp = newHead;
        for (int i = 1; i < right - left + 2; i++) {
            next = newHead.next;
            newHead.next = prev;
            prev = newHead;
            newHead = next;
        }
        pprev.next = prev;
        tmp.next = next;
        return cur.next;
    }
}